import {
    action,
    computed,
    makeAutoObservable
} from 'mobx';
// 导入http.js
import axios from '../utils/http';

class AppStore {
    // 将品牌列表数组转换为可观察对象
    brandList = [
        // {
        //     id:2,
        //     name:'蔚来',
        //     ctime:Date.now()
        // },
        // {
        //     id:1,
        //     name:'特斯拉',
        //     ctime:Date.now()
        // }
    ];

    constructor() {
        // 将所有的属性变为可观察对象
        makeAutoObservable(this);
    }

    @computed get brandCount() {
        return this.brandList.length;
    }


    // 初始化品牌列表
    @action brandListInit() {
        axios.get('/brandList').then(data => {
            if (data.code === 200) {
                this.brandList = data.list;
            }
        })
    }

    // 新增品牌
    @action brandAdd(name) {
        // 发送数据请求
        axios.post('/brandAdd', {
            name
        }).then(data => {
            if (data.code === 200) {
                const id = data.id;
                const row = {
                    id,
                    name,
                    ctime: Date.now()
                };
                this.brandList.unshift(row);
            }
        });
    }
    // 编辑品牌
    @action brandUpdate(row) {

        axios.post('/brandUpdate/' + row.id, {
            name: row.name
        }).then(data => {
            if (data.code === 200) {
                // 更新本地数据
                const index = this.brandList.findIndex(item => item.id === row.id);
                this.brandList[index].name = row.name;
                this.brandList[index].ctime = Date.now();
            }
        });
    }
    // 删除品牌
    @action brandDel(id) {

        axios.get('/brandDel/'+id).then(data => {
            if (data.code === 200) {
                const index = this.brandList.findIndex(item => item.id === id);
                this.brandList.splice(index, 1);
            }
        });

    }
}

const store = new AppStore();
// 导出store存储对象
export default store;